/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.rpc.workflow.user;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.SecurityUserHolder;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.rpc.workflow.user.special.SpecialUserParserEnum;
import com.je.rbac.service.IconType;
import org.apache.commons.lang.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门、人员树
 */
public class ParserDepartmentJsonTreeFilter extends FilterChain implements Filter {

    @Override
    public void handler(ParserUserBo parserUserBo, JSONTreeNode jsonTreeNode , FilterChain filterChain) {

        List<String> types = parserUserBo.getTypes();
        //选择类型不为空
        if (types != null && types.size() > 0) {
            //包含本部门内人员 、或者本部门内含子部门人员 监管部门内人员 则渲染公司、人员树
            if (!types.contains(SpecialUserParserEnum.DEPT_USERS.toString())
                    && !types.contains(SpecialUserParserEnum.DEPT_ALL_USERS.toString())
                    && !types.contains(SpecialUserParserEnum.DEPT_MONITOR_USERS.toString())) {
                filterChain.doFilter(parserUserBo,jsonTreeNode,filterChain);
                return;
            }
            DynaBean dynaBean = findVacCountDeptUserById(parserUserBo.getUserId());
            DynaBean deptmentBean = metaService.selectOne("JE_RBAC_DEPARTMENT",
                    ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", dynaBean.get("ACCOUNTDEPT_DEPT_ID")));
            List<String> monitorDeptIds = null;
            if (null != deptmentBean.get("DEPARTMENT_MONITORDEPT_ID")) {
                //所在部门监管的部门id
                monitorDeptIds = Splitter.on(",").splitToList(deptmentBean.get("DEPARTMENT_MONITORDEPT_ID").toString());
            }
            //已经有了公司部门人员树，看所选监管部门内人员 在不在公司树上，如果不在新建公司部门人员树
            if (parserUserBo.getCompanyDeptUserTree() || parserUserBo.getCompanyUserTree()) {
                if (null != monitorDeptIds && monitorDeptIds.size() > 0) {
                    //所在部门监管的部门id
                    //公司部门人员 树上 没有的部门 Id
                    List<String> otherDepartmentIds = new ArrayList<>();
                    for (String deptId : monitorDeptIds) {
                        if (JsonTreeContext.getJsonTree(deptId) == null) {
                            otherDepartmentIds.add(deptId);
                        }
                    }

                    List<DynaBean> userBeanList;
                    if (otherDepartmentIds.size() > 0) {
                        //部门下人员信息
                        userBeanList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_DEPT_ID", otherDepartmentIds).eq("SY_STATUS","1").orderByAsc("SY_ORDERINDEX"));
                        if (!parserUserBo.getAddOwn()) {
                            userBeanList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_DEPT_ID", otherDepartmentIds)
                                    .ne("JE_RBAC_ACCOUNTDEPT_ID", SecurityUserHolder.getCurrentAccount().getDeptId()).eq("SY_STATUS","1").orderByAsc("SY_ORDERINDEX"));
                        }
                        if (null != userBeanList && !userBeanList.isEmpty()) {
                            //根据部门id分组
                            Map<String, List<DynaBean>> deptListMap = userBeanList.stream().collect(Collectors.groupingBy(bean -> bean.getStr("ACCOUNTDEPT_DEPT_ID")));

                            //查找部门所属公司，在不在树上，并构建公司部门人员信息
                            checkCompany(deptListMap, parserUserBo.getMultiple());
                        }

                    }
                }
                //去除重复选择
                //当前登录人
                parserUserBo.getTypes().remove(SpecialUserParserEnum.LOGINED_USER.toString());
                //本部门内
                parserUserBo.getTypes().remove(SpecialUserParserEnum.DEPT_USERS.toString());
                //本部门内含子部门
                parserUserBo.getTypes().remove(SpecialUserParserEnum.DEPT_ALL_USERS.toString());
                //监管部门
                parserUserBo.getTypes().remove(SpecialUserParserEnum.DEPT_MONITOR_USERS.toString());

            } else {
                //如果没有公司信息，构建部门人员树
                //监管部门id

                //所在部门id
                List<String> deptIdList = Splitter.on(",").splitToList(dynaBean.getStr("ACCOUNTDEPT_DEPT_ID"));
                //部门、子部门
                List<String> myDeptIdList = rbacDepartmentService.findAllPathDepartments(StringUtils.join(deptIdList, ","));

                List<DynaBean> allDeptBeanList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().in("JE_RBAC_DEPARTMENT_ID", myDeptIdList).apply("ORDER BY SY_TREEORDERINDEX ASC , SY_ORDERINDEX ASC"));

                DynaBean deptBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().in("JE_RBAC_DEPARTMENT_ID", dynaBean.getStr("ACCOUNTDEPT_DEPT_ID")));

                DynaBean table = beanService.getResourceTable("JE_RBAC_DEPARTMENT");
                List<DynaBean> columns = (List<DynaBean>) table.get(BeanService.KEY_TABLE_COLUMNS);
                JSONTreeNode template = beanService.buildJSONTreeNodeTemplate(columns);
                //所在部门子部门
                if (types.contains(SpecialUserParserEnum.DEPT_ALL_USERS.toString())) {

                    //构建父部门树
                    JSONTreeNode parentNode = buildDeptTreeNode(template, "ROOT", deptBean);
                    //节点信息类型
                    parentNode.setNodeInfo("department");
                    parentNode.setNodeInfoType("department");
                    JsonTreeContext.putJsonTree(parentNode.getId(), parentNode);
                    JsonTreeContext.getJsonTree("ROOT").getChildren().add(parentNode);
                    List<DynaBean> accountDeptBeanList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_DEPT_ID", myDeptIdList).eq("SY_STATUS", "1").orderByAsc("SY_ORDERINDEX"));
                    if (!parserUserBo.getAddOwn()) {
                        accountDeptBeanList = accountDeptBeanList.stream().filter(x -> !(x.getStr("JE_RBAC_ACCOUNTDEPT_ID")
                                .equals(SecurityUserHolder.getCurrentAccount().getDeptId()))).collect(Collectors.toList());
                    }
                    //构建子部门和人员信息
                    recursiveSpecialDeptJsonTreeNode(template, parentNode, allDeptBeanList, accountDeptBeanList, parserUserBo.getMultiple());

                    //去除重复选择
                    //当前登录人
                    parserUserBo.getTypes().remove(SpecialUserParserEnum.LOGINED_USER.toString());
                    //本部门内
                    parserUserBo.getTypes().remove(SpecialUserParserEnum.DEPT_USERS.toString());
                    //本部门内含子部门
                    parserUserBo.getTypes().remove(SpecialUserParserEnum.DEPT_ALL_USERS.toString());
                }
                if (types.contains(SpecialUserParserEnum.DEPT_USERS.toString())) {
                    //所在部门
                    String deptId = dynaBean.getStr("ACCOUNTDEPT_DEPT_ID");
                    if (null == JsonTreeContext.getJsonTree(deptId)) {
                        //构建父部门树
                        JSONTreeNode parentNode = buildDeptTreeNode(template, JsonTreeContext.getJsonTree("ROOT").getId(), deptBean);
                        //节点信息类型
                        parentNode.setNodeInfo("department");
                        parentNode.setNodeInfoType("department");
                        JsonTreeContext.putJsonTree(parentNode.getId(), parentNode);
                        JsonTreeContext.getJsonTree("ROOT").getChildren().add(parentNode);
                        List<DynaBean> accountDeptBeanList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_DEPT_ID", deptIdList).eq("SY_STATUS", "1").orderByAsc("SY_ORDERINDEX"));
                        if (!parserUserBo.getAddOwn()) {
                            accountDeptBeanList = accountDeptBeanList.stream().filter(x -> !(x.getStr("JE_RBAC_ACCOUNTDEPT_ID")
                                    .equals(SecurityUserHolder.getCurrentAccount().getDeptId()))).collect(Collectors.toList());
                        }
                        //构建人员信息
                        if (accountDeptBeanList != null && accountDeptBeanList.size() > 0) {
                            for (DynaBean eachAccoutDeptBean : accountDeptBeanList) {
                                if (parentNode.getBean().get("JE_RBAC_DEPARTMENT_ID").equals(eachAccoutDeptBean.getStr("ACCOUNTDEPT_DEPT_ID"))) {
                                    //构建当前部门下人员信息
                                    parseAccountDepartmentToTree(parentNode, eachAccoutDeptBean, parserUserBo.getMultiple(), true);
                                }
                            }
                        }
                    }
                    //去除重复选择
                    //当前登录人
                    parserUserBo.getTypes().remove(SpecialUserParserEnum.LOGINED_USER.toString());
                    //本部门内
                    parserUserBo.getTypes().remove(SpecialUserParserEnum.DEPT_USERS.toString());

                }
                if (types.contains(SpecialUserParserEnum.DEPT_MONITOR_USERS.toString())) {
                    //监管部门
                    if (null != monitorDeptIds && monitorDeptIds.size() > 0) {
                        //所在部门监管的部门id
                        //公司部门人员 树上 没有的部门 Id
                        List<String> otherDepartmentIds = new ArrayList<>();
                        for (String deptId : monitorDeptIds) {
                            if (JsonTreeContext.getJsonTree(deptId) == null) {
                                otherDepartmentIds.add(deptId);
                            }
                        }

                        List<DynaBean> userBeanList;
                        if (otherDepartmentIds.size() > 0) {
                            //部门下人员信息
                            userBeanList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_DEPT_ID", otherDepartmentIds).eq("SY_STATUS","1").orderByAsc("SY_ORDERINDEX"));
                            if (!parserUserBo.getAddOwn()) {
                                userBeanList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_DEPT_ID", otherDepartmentIds)
                                        .ne("JE_RBAC_ACCOUNTDEPT_ID", SecurityUserHolder.getCurrentAccount().getDeptId()).eq("SY_STATUS","1").orderByAsc("SY_ORDERINDEX"));
                            }
                            if (null != userBeanList && !userBeanList.isEmpty()) {
                                //根据部门id分组
                                Map<String, List<DynaBean>> deptListMap = userBeanList.stream().collect(Collectors.groupingBy(bean -> bean.getStr("ACCOUNTDEPT_DEPT_ID")));
                                Set<String> departmentIds = deptListMap.keySet();
                                for (String departmentId : departmentIds) {
                                    //构建部门人员信息
                                    buildDeptUserTree(deptListMap, parserUserBo.getMultiple(), departmentId, JsonTreeContext.getJsonTree("ROOT"));
                                }
                            }

                        }
                    }
                    //去除重复选择
                    //监管部门
                    parserUserBo.getTypes().remove(SpecialUserParserEnum.DEPT_MONITOR_USERS.toString());

                }
                parserUserBo.setDeptUserTree(true);
            }
            filterChain.doFilter(parserUserBo,jsonTreeNode,filterChain);

        }
    }





}
